package com.clp.protocol.core.utils;

import com.clp.protocol.core.exception.EnumElemDoesNotExistException;
import lombok.Getter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Getter
public enum DateFormatter {
    yyyyMMddHHmmssSSS("yyyy-MM-dd HH:mm:ss.SSS");

    private final String expr;
    private final DateFormat dateFormat;

    DateFormatter(String expr) {
        this.expr = expr;
        this.dateFormat = new SimpleDateFormat(expr);
    }

    /**
     * 输出指定的日期格式化字符串
     * @param date
     * @return
     */
    public String format(Date date) {
        synchronized (dateFormat) {
            return dateFormat.format(date);
        }
    }

    public Date parseDefaultNull(String dateStr) {
        synchronized (dateFormat) {
            try {
                return dateFormat.parse(dateStr);
            } catch (ParseException e) {
                return null;
            }
        }
    }

    public Date parseDefaultZero(String dateStr) {
        Date retDate = parseDefaultNull(dateStr);
        return retDate != null ? retDate : new Date(0);
    }

    public Date parseDefaultNow(String dateStr) {
        Date retDate = parseDefaultNull(dateStr);
        return retDate != null ? retDate : new Date();
    }

    public static DateFormatter gain(String expr) {
        for (DateFormatter dateFormatter : DateFormatter.values()) {
            if (dateFormatter.expr.equals(expr)) {
                return dateFormatter;
            }
        }
        throw new EnumElemDoesNotExistException(DateFormatter.class);
    }
}
